package com.google.code.mergeinformer.util;

import com.google.code.mergeinformer.model.security.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author Dmitry Golubev
 */
public class SecurityUtils {

    private SecurityUtils() {
    }

    /**
     * Check if user is authenticated
     * <br/>
     * Anonymous user is treated as unauthenticated!
     *
     * @return true if user is authenticated, false otherwise
     */
    public static boolean isAuthenticated() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.getPrincipal() instanceof UserDetails;
    }

    /**
     * Returns authenticated user
     *
     * @return authenticated {@link com.google.code.mergeinformer.model.security.User} or null if user is not authenticated
     */
    public static User getCurrentUser() {
        if (isAuthenticated()) {
            return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        return null;
    }

    /**
     * Update authenticated user's properties
     * @param user user containing updated properties
     * @return user with current properties stored in security context before update
     */
    public static User updateAuthenticatedUser(User user) {
        final User currentUser = getCurrentUser();
        if (!user.equals(getCurrentUser())) {
            throw new IllegalArgumentException("Attempt to replace authenticated user with another one!\n" +
                    "Current idUser=" + currentUser.getId() + "\n" +
                    "Passed  idUser=" + user.getId());
        }
        final Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return currentUser;
    }
}
